use super::db;
use super::request::{ControlCore, CoreControlSearch};
use super::response::{ControlCoreInfo, ControlCoreList};

// 新增
pub async fn create_core(data: &ControlCore) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let res = sqlx::query("INSERT INTO tb_control_core (name, model, power, price, core_img,remark,created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?,NOW(), NOW())")
    .bind(&data.name)
    .bind(&data.model)
    .bind(&data.power)
    .bind(&data.price)
    .bind(&data.core_img)
    .bind(&data.remark)
    .execute(pool).await;
    match res {
        Ok(i) => println!("ok {:#?}", i),
        Err(e) => println!("err {:#?}", e),
    }
    Ok(())
}

// 编辑
pub async fn edit_core(data: &ControlCore) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let sql_text = "UPDATE tb_control_core SET name = ?, model = ?, power = ?, price = ?, core_img = ?, remark = ?, updated_at = NOW() WHERE id = ?";
    let res = sqlx::query(&sql_text)
        .bind(&data.name)
        .bind(&data.model)
        .bind(&data.power)
        .bind(&data.price)
        .bind(&data.core_img)
        .bind(&data.remark)
        .bind(&data.id)
        .execute(pool)
        .await;

    match res {
        Ok(i) => println!("ok {:#?}", i),
        Err(e) => println!("err {:#?}", e),
    }
    Ok(())
}

// 删除
pub async fn delete_core(id: u64) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let res = sqlx::query("DELETE FROM tb_control_core WHERE id=?")
        .bind(id)
        .execute(pool)
        .await;
    match res {
        Ok(i) => println!("ok {:#?}", i),
        Err(e) => println!("err {:#?}", e),
    }
    Ok(())
}

// 详情
pub async fn core_detail(id: u64) -> Result<ControlCoreInfo, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let res = sqlx::query_as::<_, ControlCoreInfo>("SELECT * FROM tb_control_core WHERE id=?")
        .bind(id)
        .fetch_one(pool)
        .await;
    match res {
        Ok(i) => Ok(i),
        Err(e) => Err(e),
    }
}

// pub id: u64,
// pub name: String,
// pub model: String,
// pub price: BigDecimal,
// pub core_img: String,
// pub power: String,
// pub remark: String,

// 列表
pub async fn core_list(data: &CoreControlSearch) -> Result<ControlCoreList, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let offset = (data.page - 1) * data.page_size;

    // 第一步：构建最基础的查询
    let mut query =
        "SELECT id,name,model,price,core_img,power,remark,created_at,updated_at FROM tb_control_core"
            .to_string();

    // 构建搜索条件
    let mut conditions = Vec::new();

    if let Some(id) = &data.id {
        conditions.push(format!("id = '{}'", id));
    }

    if let Some(name) = &data.name {
        conditions.push(format!("name LIKE '%{}%'", name));
    }

    if let Some(model) = &data.model {
        conditions.push(format!("model LIKE '%{}%'", model));
    }

    // 添加搜索条件到查询语句
    if !conditions.is_empty() {
        query.push_str(" WHERE ");
        query.push_str(&conditions.join(" AND "));
    }

    // 添加排序和分页限制
    query.push_str(" ORDER BY created_at DESC LIMIT ? OFFSET ?");

    println!("sql: {}", query);
    // 执行查询
    let control_core_list = sqlx::query_as::<_, ControlCoreInfo>(&query)
        .bind(data.page_size)
        .bind(offset)
        .fetch_all(pool)
        .await?;

    // 获取总条数
    let count_query = format!(
        "SELECT COUNT(*) as total FROM tb_control_core {}",
        if !conditions.is_empty() {
            format!("WHERE {}", conditions.join(" AND "))
        } else {
            "".to_string()
        }
    );
    let count_result: (Option<i64>,) = sqlx::query_as(count_query.as_str()).fetch_one(pool).await?;
    let count = count_result.0.unwrap_or(0); // 空结果处理

    let res = ControlCoreList {
        list: control_core_list,
        total: count,
    };

    Ok(res)
}
